package com.management.department.teacherinfosystem.Service;

import com.management.department.teacherinfosystem.DTO.AcademicAchievementSubmitDTO;
import com.management.department.teacherinfosystem.DTO.AcademicAchievementDTO;
import com.management.department.teacherinfosystem.Entity.AcademicAchievement;
import com.management.department.teacherinfosystem.Entity.AcademicAchievementAuthor;
import com.management.department.teacherinfosystem.Entity.AcademicAchievementAttachment;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementRepository;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementAuthorRepository;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementAttachmentRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class AcademicAchievementServiceImpl implements AcademicAchievementService {
    
    @Value("${file.upload.academic-dir:uploads/academic_achievements/}")
    private String uploadDir;
    
    @Autowired
    private AcademicAchievementRepository achievementRepository;
    
    @Autowired
    private AcademicAchievementAuthorRepository authorRepository;
    
    @Autowired
    private AcademicAchievementAttachmentRepository attachmentRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    @Transactional
    public AcademicAchievement createAchievement(AcademicAchievementSubmitDTO dto, MultipartFile[] files) throws Exception {
        // 创建学术成果
        AcademicAchievement achievement = new AcademicAchievement();
        achievement.setTitle(dto.getTitle());
        achievement.setType(dto.getType());
        achievement.setLanguage(dto.getLanguage());
        achievement.setKeywords(dto.getKeywords());
        achievement.setJournalConference(dto.getJournalConference());
        achievement.setPublicationYear(dto.getPublicationYear());
        achievement.setPublicationMonth(dto.getPublicationMonth());
        achievement.setDoi(dto.getDoi());
        achievement.setJournalLevel(dto.getJournalLevel());
        achievement.setConferenceLevel(dto.getConferenceLevel());
        achievement.setStatus("PENDING");
        
        // 设置创建者ID
        if (dto.getCreatedBy() != null) {
            achievement.setCreatedBy(dto.getCreatedBy());
        } else {
            throw new RuntimeException("创建者ID不能为空");
        }
        
        // 保存学术成果
        achievement = achievementRepository.save(achievement);
        
        // 保存作者信息
        if (dto.getAuthors() != null) {
            for (AcademicAchievementSubmitDTO.AcademicAuthorDTO authorDto : dto.getAuthors()) {
                AcademicAchievementAuthor author = new AcademicAchievementAuthor();
                author.setAchievementId(achievement.getId());
                author.setAuthorName(authorDto.getAuthorName());
                author.setAuthorUnit(authorDto.getAuthorUnit());
                author.setAuthorOrder(authorDto.getAuthorOrder());
                author.setIsCurrentUnit(authorDto.getIsCurrentUnit());
                author.setStaffNo(authorDto.getStaffNo());
                author.setIsCurrentDepartment(authorDto.getIsCurrentDepartment());
                authorRepository.save(author);
            }
        }
        
        // 处理附件
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    uploadAttachment(achievement.getId(), file, "证明材料");
                }
            }
        }
        
        return achievement;
    }
    
    @Override
    @Transactional
    public AcademicAchievement updateAchievement(Long id, AcademicAchievementSubmitDTO dto, MultipartFile[] files) throws Exception {
        AcademicAchievement achievement = achievementRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("学术成果不存在"));
        
        // 更新基本信息
        achievement.setTitle(dto.getTitle());
        achievement.setType(dto.getType());
        achievement.setLanguage(dto.getLanguage());
        achievement.setKeywords(dto.getKeywords());
        achievement.setJournalConference(dto.getJournalConference());
        achievement.setPublicationYear(dto.getPublicationYear());
        achievement.setPublicationMonth(dto.getPublicationMonth());
        achievement.setDoi(dto.getDoi());
        achievement.setJournalLevel(dto.getJournalLevel());
        achievement.setConferenceLevel(dto.getConferenceLevel());
        
        // 重置状态为待审核，清除审核信息
        achievement.setStatus("PENDING");
        achievement.setReviewOpinion(null);
        achievement.setReviewerId(null);
        achievement.setReviewTime(null);
        
        // 保存更新
        achievement = achievementRepository.save(achievement);
        
        // 删除旧的作者信息
        authorRepository.deleteByAchievementId(id);
        
        // 保存新的作者信息
        if (dto.getAuthors() != null) {
            for (AcademicAchievementSubmitDTO.AcademicAuthorDTO authorDto : dto.getAuthors()) {
                AcademicAchievementAuthor author = new AcademicAchievementAuthor();
                author.setAchievementId(achievement.getId());
                author.setAuthorName(authorDto.getAuthorName());
                author.setAuthorUnit(authorDto.getAuthorUnit());
                author.setAuthorOrder(authorDto.getAuthorOrder());
                author.setIsCurrentUnit(authorDto.getIsCurrentUnit());
                author.setStaffNo(authorDto.getStaffNo());
                author.setIsCurrentDepartment(authorDto.getIsCurrentDepartment());
                authorRepository.save(author);
            }
        }
        
        // 处理附件
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    uploadAttachment(achievement.getId(), file, "证明材料");
                }
            }
        }
        
        return achievement;
    }
    
    @Override
    @Transactional
    public void deleteAchievement(Long id) throws Exception {
        // 删除附件文件
        List<AcademicAchievementAttachment> attachments = attachmentRepository.findByAchievementId(id);
        for (AcademicAchievementAttachment attachment : attachments) {
            try {
                Path filePath = Paths.get(attachment.getFileUrl());
                Files.deleteIfExists(filePath);
            } catch (IOException e) {
                // 忽略文件删除错误
            }
        }
        
        // 删除数据库记录（级联删除）
        achievementRepository.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public AcademicAchievement getAchievementById(Long id) {
        return achievementRepository.findById(id).orElse(null);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievement> getMyAchievements(Long userId) {
        return achievementRepository.findByCreatedBy(userId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievement> getAllAchievements() {
        return achievementRepository.findAll();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievement> getPendingAchievements() {
        return achievementRepository.findByStatus("PENDING");
    }
    
    @Override
    @Transactional(readOnly = true)
    public AcademicAchievementDTO getAchievementDTOById(Long id) {
        AcademicAchievement achievement = achievementRepository.findById(id).orElse(null);
        if (achievement == null) {
            return null;
        }
        return convertToDTO(achievement);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievementDTO> getMyAchievementsDTO(Long userId) {
        List<AcademicAchievement> achievements = achievementRepository.findByCreatedBy(userId);
        return achievements.stream().map(this::convertToDTO).toList();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievementDTO> getAllAchievementsDTO() {
        List<AcademicAchievement> achievements = achievementRepository.findAll();
        return achievements.stream().map(this::convertToDTO).toList();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AcademicAchievementDTO> getPendingAchievementsDTO() {
        List<AcademicAchievement> achievements = achievementRepository.findByStatus("PENDING");
        return achievements.stream().map(this::convertToDTO).toList();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getTeachersList() {
        // 从学术成果中获取所有创建者信息
        List<AcademicAchievement> achievements = achievementRepository.findAll();
        return achievements.stream()
            .filter(achievement -> achievement.getCreatedBy() != null)
            .map(achievement -> {
                Map<String, Object> teacher = new HashMap<>();
                teacher.put("id", achievement.getCreatedBy());
                
                // 尝试从用户表获取真实姓名
                try {
                    var user = userRepository.findById(achievement.getCreatedBy());
                    if (user.isPresent()) {
                        // 优先使用真实姓名字段，如果没有则使用用户名
                        String realName = user.get().getName();
                        if (realName != null && !realName.trim().isEmpty()) {
                            teacher.put("name", realName);
                        } else {
                            teacher.put("name", user.get().getUsername());
                        }
                    } else {
                        teacher.put("name", "用户" + achievement.getCreatedBy());
                    }
                } catch (Exception e) {
                    teacher.put("name", "用户" + achievement.getCreatedBy());
                }
                
                return teacher;
            })
            .distinct()
            .collect(Collectors.toList());
    }
    
    // 根据作者姓名搜索成果ID列表
    @Override
    @Transactional(readOnly = true)
    public List<Long> getAchievementIdsByAuthorName(String authorName) {
        if (authorName == null || authorName.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        List<AcademicAchievementAuthor> authors = authorRepository.findByAuthorNameContaining(authorName.trim());
        return authors.stream()
            .map(AcademicAchievementAuthor::getAchievementId)
            .distinct()
            .collect(Collectors.toList());
    }
    
    // 转换为DTO的辅助方法
    private AcademicAchievementDTO convertToDTO(AcademicAchievement achievement) {
        AcademicAchievementDTO dto = new AcademicAchievementDTO();
        dto.setId(achievement.getId());
        dto.setTitle(achievement.getTitle());
        dto.setType(achievement.getType());
        dto.setLanguage(achievement.getLanguage());
        dto.setKeywords(achievement.getKeywords());
        dto.setJournalConference(achievement.getJournalConference());
        dto.setPublicationYear(achievement.getPublicationYear());
        dto.setPublicationMonth(achievement.getPublicationMonth());
        dto.setDoi(achievement.getDoi());
        dto.setJournalLevel(achievement.getJournalLevel());
        dto.setConferenceLevel(achievement.getConferenceLevel());
        dto.setStatus(achievement.getStatus());
        dto.setReviewOpinion(achievement.getReviewOpinion());
        dto.setReviewerId(achievement.getReviewerId());
        dto.setReviewTime(achievement.getReviewTime());
        dto.setCreatedBy(achievement.getCreatedBy());
        dto.setCreatedAt(achievement.getCreatedAt());
        dto.setUpdatedAt(achievement.getUpdatedAt());
        
        // 获取作者信息
        List<AcademicAchievementAuthor> authors = authorRepository.findByAchievementId(achievement.getId());
        dto.setAuthors(authors.stream().map(this::convertAuthorToDTO).toList());
        
        // 获取附件信息
        List<AcademicAchievementAttachment> attachments = attachmentRepository.findByAchievementId(achievement.getId());
        dto.setAttachments(attachments.stream().map(this::convertAttachmentToDTO).toList());
        
        return dto;
    }
    
    private AcademicAchievementDTO.AcademicAuthorDTO convertAuthorToDTO(AcademicAchievementAuthor author) {
        AcademicAchievementDTO.AcademicAuthorDTO dto = new AcademicAchievementDTO.AcademicAuthorDTO();
        dto.setId(author.getId());
        dto.setAuthorName(author.getAuthorName());
        dto.setAuthorUnit(author.getAuthorUnit());
        dto.setAuthorOrder(author.getAuthorOrder());
        dto.setIsCurrentUnit(author.getIsCurrentUnit());
        dto.setStaffNo(author.getStaffNo());
        dto.setIsCurrentDepartment(author.getIsCurrentDepartment());
        dto.setCreatedAt(author.getCreatedAt());
        return dto;
    }
    
    private AcademicAchievementDTO.AcademicAttachmentDTO convertAttachmentToDTO(AcademicAchievementAttachment attachment) {
        AcademicAchievementDTO.AcademicAttachmentDTO dto = new AcademicAchievementDTO.AcademicAttachmentDTO();
        dto.setId(attachment.getId());
        dto.setFileName(attachment.getFileName());
        dto.setFileUrl(attachment.getFileUrl());
        dto.setFileType(attachment.getFileType());
        dto.setFileSize(attachment.getFileSize());
        dto.setCreatedAt(attachment.getCreatedAt());
        return dto;
    }
    

    
    @Override
    @Transactional
    public void reviewAchievement(Long id, String status, String opinion, Long reviewerId) {
        AcademicAchievement achievement = achievementRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("学术成果不存在"));
        
        achievement.setStatus(status);
        achievement.setReviewOpinion(opinion);
        achievement.setReviewerId(reviewerId);
        achievement.setReviewTime(new java.util.Date());
        
        achievementRepository.save(achievement);
    }
    
    @Override
    public void uploadAttachment(Long achievementId, MultipartFile file, String fileType) throws Exception {
        // 创建上传目录
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path filePath = Paths.get(uploadDir + filename);
        Files.copy(file.getInputStream(), filePath);
        
        // 保存附件信息到数据库
        AcademicAchievementAttachment attachment = new AcademicAchievementAttachment();
        attachment.setAchievementId(achievementId);
        attachment.setFileName(originalFilename);
        attachment.setFileUrl(uploadDir + filename);
        attachment.setFileType(fileType);
        attachment.setFileSize(file.getSize());
        
        attachmentRepository.save(attachment);
    }
    
    @Override
    public void deleteAttachment(Long attachmentId) {
        AcademicAchievementAttachment attachment = attachmentRepository.findById(attachmentId)
                .orElseThrow(() -> new RuntimeException("附件不存在"));
        
        // 删除文件
        try {
            Path filePath = Paths.get(attachment.getFileUrl());
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            // 忽略文件删除错误
        }
        
        // 删除数据库记录
        attachmentRepository.deleteById(attachmentId);
    }
}
